/*
 * Copyright (c) 2023 Huawei Technologies Co., Ltd.
 * openUBMC is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *         http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */

#include <mc/log.h>

#include "interface/network_port/link_info.h"

namespace dev {

bool NetworkPort_LinkInfo::update_link_status_by_ncsi(uint8_t port_id) {
    if (!m_ncsi_over_mctp_mellanox) {
        elog("Error: NCSI over MCTP not initialized when updating link status");
        return false;
    }
    ncsi_link_status_info_t link_status = {};
    bool ret = m_ncsi_over_mctp_mellanox->get_link_status(m_package_id, port_id, &link_status);
    if (!ret) {       
        LinkStatus.set_value(255);  // 无效值
        SpeedMbps.set_value(0);
        FullDuplex.set_value(false);
        return false;
    }

    LinkStatus.set_value(link_status.link_status);
    SpeedMbps.set_value(link_status.speed_mbps);
    FullDuplex.set_value(link_status.full_duplex ? true : false);
    return true;
}

void NetworkPort_LinkInfo::start_ncsi_update_task_mellanox(ncsi_over_mctp_mellanox_ptr ncsi_over_mctp,
                                                         mc::milliseconds      interval,
                                                         uint8_t               port_id,
                                                         uint8_t               package_id) {
    m_ncsi_over_mctp_mellanox = ncsi_over_mctp;
    m_ncsi_timer            = new mc::core::timer(this);
    m_package_id = package_id;
    m_ncsi_timer->timeout.connect([this, port_id]() {
        update_link_status_by_ncsi(port_id);
    });
    m_ncsi_timer->set_single_shot(false);
    m_ncsi_timer->start(interval);
}

void NetworkPort_LinkInfo::stop_ncsi_update_task() {
    if (m_ncsi_timer) {
        m_ncsi_timer->stop();
    }
    if (m_ncsi_over_mctp_mellanox) {
        m_ncsi_over_mctp_mellanox = nullptr;
    }
}

} // namespace dev

MC_REFLECT(dev::NetworkPort_LinkInfo)